package com.ruoyi.archive.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.archive.mapper.ArchivePersonMapper;
import com.ruoyi.archive.domain.ArchivePerson;
import com.ruoyi.archive.service.IArchivePersonService;

/**
 * 业主信息Service业务层处理
 *
 * @author yepanpan
 * @date 2025-04-17
 */
@Service
public class ArchivePersonServiceImpl implements IArchivePersonService
{
    private static final Logger log = LoggerFactory.getLogger(ArchivePersonServiceImpl.class);

    @Autowired
    private ArchivePersonMapper archivePersonMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询业主信息
     *
     * @param id 业主信息主键
     * @return 业主信息
     */
    @Override
    public ArchivePerson selectArchivePersonById(Long id)
    {
        return archivePersonMapper.selectArchivePersonById(id);
    }

    /**
     * 查询业主信息列表
     *
     * @param archivePerson 业主信息
     * @return 业主信息
     */
    @Override
    public List<ArchivePerson> selectArchivePersonList(ArchivePerson archivePerson)
    {
        return archivePersonMapper.selectArchivePersonList(archivePerson);
    }

    /**
     * 新增业主信息
     *
     * @param archivePerson 业主信息
     * @return 结果
     */
    @Override
    public int insertArchivePerson(ArchivePerson archivePerson)
    {
        ArchivePerson old = archivePersonMapper.selectArchivePersonByCard(archivePerson.getCard());
        if(old != null){
            throw new ServiceException("身份证号已存在: " + archivePerson.getCard());
        }
        archivePerson.setCreateTime(DateUtils.getNowDate());
        return archivePersonMapper.insertArchivePerson(archivePerson);
    }

    /**
     * 修改业主信息
     *
     * @param archivePerson 业主信息
     * @return 结果
     */
    @Override
    public int updateArchivePerson(ArchivePerson archivePerson)
    {
        ArchivePerson old = archivePersonMapper.selectArchivePersonByCard(archivePerson.getCard());
        if(old != null && !old.getId().equals(archivePerson.getId())){
            throw new ServiceException("身份证号已存在: " + archivePerson.getCard());
        }
        archivePerson.setUpdateTime(DateUtils.getNowDate());
        return archivePersonMapper.updateArchivePerson(archivePerson);
    }

    /**
     * 批量删除业主信息
     *
     * @param ids 需要删除的业主信息主键
     * @return 结果
     */
    @Override
    public int deleteArchivePersonByIds(Long[] ids)
    {
        return archivePersonMapper.deleteArchivePersonByIds(ids);
    }

    /**
     * 删除业主信息信息
     *
     * @param id 业主信息主键
     * @return 结果
     */
    @Override
    public int deleteArchivePersonById(Long id)
    {
        return archivePersonMapper.deleteArchivePersonById(id);
    }


    /**
     * 导入数据
     *
     * @param dataList 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importData(List<ArchivePerson> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ArchivePerson row : dataList)
        {
            try
            {
                if(!row.getType().equalsIgnoreCase("1") && StringUtils.isNotEmpty(row.getRelCard())){
                    ArchivePerson relPerson = archivePersonMapper.selectArchivePersonByCard(row.getRelCard());
                    if(relPerson == null){
                        throw new ServiceException("户主不存在："+row.getRelCard());
                    }else {
                        row.setRelId(relPerson.getId());
                    }
                }

                BeanValidators.validateWithException(validator, row);

                // 验证是否存在旧数据
                ArchivePerson old = archivePersonMapper.selectArchivePersonByCard(row.getCard());
                if (StringUtils.isNull(old))
                {
                    row.setCreateBy(operName);
                    insertArchivePerson(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、业主 " + row.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    row.setUpdateBy(operName);
                    row.setId(old.getId());
                    updateArchivePerson(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、业主 " + row.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、业主 " + row.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、业主 " + row.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
